package com.example.qxfw.nyqx.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.qxfw.nyqx.dto.AgriSrvFcstDto;
import com.example.qxfw.nyqx.mapper.AgriProductMapper;
import com.example.qxfw.nyqx.mapper.AgriSrvFcstMapper;
import com.example.qxfw.common.entity.ny.AgriServiceIndex;
import com.example.qxfw.common.entity.ny.AgriSrvFcst;
import com.example.qxfw.common.entity.ny.StationInfo;
import com.example.qxfw.common.entity.qx.MsgMediumSmallScale;
import com.example.qxfw.common.entity.qx.TownshipForecast;
import com.example.qxfw.common.entity.qx.TownshipStation;
import com.example.qxfw.nyqx.dto.AgriStationDto;
import com.example.qxfw.nyqx.dto.MappingStation;
import com.example.qxfw.nyqx.service.AgriServiceIndexService;
import com.example.qxfw.nyqx.service.AgriSrvFcstService;
import com.example.qxfw.nyqx.service.DailyAgriculturalForecastService;
import com.example.qxfw.common.entity.zy.AgriProduct;
import com.example.qxfw.common.util.DateUtil;
import com.example.qxfw.mongodb.hy.entity.HyDocFile;
import com.example.qxfw.mongodb.hy.service.DocFileService;
import com.example.qxfw.rcyw.mapper.StationInfoMapper;
import com.example.qxfw.ybzz.mapper.MsgMediumSmallScaleMapper;
import com.example.qxfw.ybzz.mapper.TownshipForecastMapper;
import com.example.qxfw.ybzz.mapper.TownshipStationMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.*;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

import static com.example.qxfw.common.util.DocxUtil.replaceTextInParagraph;

@Slf4j
@Service
public class DailyAgriculturalForecastServiceImpl implements DailyAgriculturalForecastService {

    @Value("${filePath.ip}")
    private String ip;

    @Value("${filePath.port}")
    private String port;

    @Value("${filePath.docFilePath}")
    private String docFilePath;

    @Autowired
    private AgriProductMapper agriProductMapper;

    @Autowired
    private TownshipStationMapper townshipStationMapper;

    @Autowired
    private TownshipForecastMapper townshipForecastMapper;

    @Autowired
    private StationInfoMapper stationInfoMapper;

    @Autowired
    private AgriServiceIndexService agriServiceIndexService;

    @Autowired
    private MsgMediumSmallScaleMapper msgMediumSmallScaleMapper;

    @Autowired
    private AgriSrvFcstService agriSrvFcstService;

    @Autowired
    private AgriSrvFcstMapper agriSrvFcstMapper;

    @Value("${city}")
    private String city;

    @Autowired
    private DocFileService docFileService;

    @Override
    public boolean ybzz(String indexName, String dateChar, String timeChar) throws ParseException {
        //获取区域自动站点数据
        List<TownshipStation> townshipStations = townshipStationMapper.selectList(Wrappers.<TownshipStation>query()
                .select("distinct stationid", "stationname", "Longitude", "Latitude")
                .lambda()
                .like(TownshipStation::getCity, city));

        //获取农业站点数据
        List<StationInfo> stationInfos = stationInfoMapper.selectList(Wrappers.<StationInfo>query()
                .select("stationid", "stationname", "county", "lon", "lat"));

        //得到站点映射
        List<MappingStation> mappingStations = new ArrayList<>();
        for (StationInfo stationInfo : stationInfos) {
            TownshipStation nearStation = getNearStation(stationInfo.getLon(), stationInfo.getLat(), townshipStations);
            MappingStation mappingStation = new MappingStation();
            mappingStation.setStrStaID(nearStation.getStationid());
            mappingStation.setStrsataioncode(stationInfo.getStationid());
            mappingStation.setStrAgrSta(stationInfo.getStationname());
            mappingStation.setStrAgrCounty(stationInfo.getCounty());
            mappingStation.setDAgrLon(stationInfo.getLon());
            mappingStation.setDAgrLat(stationInfo.getLat());
            System.out.println(mappingStation);
            mappingStations.add(mappingStation);
        }


        //删除之前活动预报
        agriSrvFcstService.delete(dateChar, timeChar, indexName);

        //农事活动预报
        List<TownshipForecast> townshipForecasts = townshipForecastMapper.selectList(Wrappers.<TownshipForecast>query()
                .select("distinct stationid")
                .lambda()
                .eq(TownshipForecast::getDatechar, Timestamp.valueOf(dateChar))
                .eq(TownshipForecast::getTimechar, timeChar));
        if (townshipForecasts.size()==0){
            return false;
        }
        int count = 0, countc = 0;
        for (TownshipForecast townshipForecast : townshipForecasts) {
            //与此区域站对应的农业站点列表
            List<AgriStationDto> agriStations = getAgriStations(townshipForecast.getStationid(), mappingStations);
            if (agriStations.size() > 0) {
                for (AgriStationDto agriStation : agriStations) {
                    //判断是否为适宜作业
                    List<AgriServiceIndex> agriServiceIndices = agriServiceIndexService.getList(indexName, "适宜");

                    count = 0;
                    int tableCount = 0;
                    for (int i = 0; i < agriServiceIndices.size(); i++) {
                        tableCount++;
                        if (agriServiceIndices.get(i).getConditiontype().equals("预报")) {
                            if (agriServiceIndices.get(i).getWeatherelement().equals("降水")) {
                                String applystr = "";
                                if(agriServiceIndices.get(i).getCondition().contains("<=")){
                                    applystr = "Rain <= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains("<")){
                                    applystr = "Rain < " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">=")){
                                    applystr = "Rain >= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">")){
                                    applystr = "Rain > " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">",""));
                                }
                                List<TownshipForecast> rainData = townshipForecastMapper.selectList(Wrappers.<TownshipForecast>query()
                                        .select("Rain")
                                        .apply(applystr)
                                        .lambda()
                                        .eq(TownshipForecast::getDatechar, Timestamp.valueOf(dateChar))
                                        .eq(TownshipForecast::getTimechar, timeChar)
                                        .eq(TownshipForecast::getNtimes, Integer.parseInt(agriServiceIndices.get(i).getNtimes()))
                                        .eq(TownshipForecast::getStationid, townshipForecast.getStationid()));
                                if (rainData.size() > 0 && rainData.get(0).getRain() != null) {
                                    count++;
                                }
                            }
                            if (agriServiceIndices.get(i).getWeatherelement().equals("温度")) {
                                String applystr = "";
                                if(agriServiceIndices.get(i).getCondition().contains("<=")){
                                    applystr = "(MaxTemp+MinTemp)/2 <= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains("<")){
                                    applystr = "(MaxTemp+MinTemp)/2 < " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">=")){
                                    applystr = "(MaxTemp+MinTemp)/2 >= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">")){
                                    applystr = "(MaxTemp+MinTemp)/2 > " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">",""));
                                }
                                List<TownshipForecast> maxTempData = townshipForecastMapper.selectList(Wrappers.<TownshipForecast>query()
                                        .select("(MaxTemp + MinTemp)/2 as MaxTemp")
                                        .apply(applystr)
                                        .lambda()
                                        .eq(TownshipForecast::getDatechar, Timestamp.valueOf(dateChar))
                                        .eq(TownshipForecast::getTimechar, timeChar)
                                        .eq(TownshipForecast::getNtimes, Integer.parseInt(agriServiceIndices.get(i).getNtimes()))
                                        .eq(TownshipForecast::getStationid, townshipForecast.getStationid()));
                                if (maxTempData.size() > 0 && maxTempData.get(0).getMaxtemp() != null) {
                                    count++;
                                }
                            }
                            if (agriServiceIndices.get(i).getWeatherelement().equals("风速")) {
                                String applystr = "";
                                if(agriServiceIndices.get(i).getCondition().contains("<=")){
                                    applystr = "WindS <= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains("<")){
                                    applystr = "WindS < " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">=")){
                                    applystr = "WindS >= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">")){
                                    applystr = "WindS > " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">",""));
                                }
                                List<TownshipForecast> windSData = townshipForecastMapper.selectList(Wrappers.<TownshipForecast>query()
                                        .select("WindS")
                                        .apply(applystr)
                                        .lambda()
                                        .eq(TownshipForecast::getDatechar, Timestamp.valueOf(dateChar))
                                        .eq(TownshipForecast::getTimechar, timeChar)
                                        .eq(TownshipForecast::getNtimes, Integer.parseInt(agriServiceIndices.get(i).getNtimes()))
                                        .eq(TownshipForecast::getStationid, townshipForecast.getStationid()));
                                if (windSData.size() > 0 && windSData.get(0).getMaxtemp() != null) {
                                    count++;
                                }
                            }
                            if (agriServiceIndices.get(i).getWeatherelement().equals("气压")) {
                                String applystr = "";
                                if(agriServiceIndices.get(i).getCondition().contains("<=")){
                                    applystr = "Press <= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains("<")){
                                    applystr = "Press < " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">=")){
                                    applystr = "Press >= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">")){
                                    applystr = "Press > " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">",""));
                                }
                                List<TownshipForecast> pressData = townshipForecastMapper.selectList(Wrappers.<TownshipForecast>query()
                                        .select("press")
                                        .apply(applystr)
                                        .lambda()
                                        .eq(TownshipForecast::getDatechar, Timestamp.valueOf(dateChar))
                                        .eq(TownshipForecast::getTimechar, timeChar)
                                        .eq(TownshipForecast::getNtimes, Integer.parseInt(agriServiceIndices.get(i).getNtimes()))
                                        .eq(TownshipForecast::getStationid, townshipForecast.getStationid()));
                                if (pressData.size() > 0 && pressData.get(0).getMaxtemp() != null) {
                                    count++;
                                }
                            }
                            if (agriServiceIndices.get(i).getWeatherelement().equals("湿度")) {
                                String applystr = "";
                                if(agriServiceIndices.get(i).getCondition().contains("<=")){
                                    applystr = "Humid <= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains("<")){
                                    applystr = "Humid < " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">=")){
                                    applystr = "Humid >= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">")){
                                    applystr = "Humid > " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">",""));
                                }
                                List<TownshipForecast> humidData = townshipForecastMapper.selectList(Wrappers.<TownshipForecast>query()
                                        .select("Humid")
                                        .apply(applystr)
                                        .lambda()
                                        .eq(TownshipForecast::getDatechar, Timestamp.valueOf(dateChar))
                                        .eq(TownshipForecast::getTimechar, timeChar)
                                        .eq(TownshipForecast::getNtimes, Integer.parseInt(agriServiceIndices.get(i).getNtimes()))
                                        .eq(TownshipForecast::getStationid, townshipForecast.getStationid()));
                                if (humidData.size() > 0 && humidData.get(0).getMaxtemp() != null) {
                                    count++;
                                }
                            }
                        } else {
                            String startDateStr = dateChar.split(" ")[0] + " " + timeChar + ":00:00";
                            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            Date startDate = sdf1.parse(startDateStr);
                            Date endDate = addHour(startDate, Integer.parseInt(agriServiceIndices.get(i).getNtimes()));
                            String endDateStr = sdf1.format(endDate);
                            if (agriServiceIndices.get(i).getWeatherelement().equals("降水")) {
                                String applystr = "";
                                if(agriServiceIndices.get(i).getCondition().contains("<=")){
                                    applystr = "sum(Rain) <= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains("<")){
                                    applystr = "sum(Rain) < " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">=")){
                                    applystr = "sum(Rain) >= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">")){
                                    applystr = "sum(Rain) > " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">",""));
                                }
                                List<MsgMediumSmallScale> msgMediumSmallScales = msgMediumSmallScaleMapper.selectList(Wrappers.<MsgMediumSmallScale>query()
                                        .select("sum(Rain) as rain")
                                        .lambda()
                                        .eq(MsgMediumSmallScale::getStationid, townshipForecast.getStationid())
                                        .between(MsgMediumSmallScale::getObservtime, Timestamp.valueOf(startDateStr), Timestamp.valueOf(endDateStr))
                                        .groupBy(MsgMediumSmallScale::getStationid, MsgMediumSmallScale::getObservtime)
                                        .having(applystr));
                                if (msgMediumSmallScales.size() > 0 && msgMediumSmallScales.get(0).getRain() != null) {
                                    count++;
                                }
                            }
                        }
                    }
                    //判断是不是不适合作业
                    List<AgriServiceIndex> agriServiceIndices1 = agriServiceIndexService.getList(indexName, "不适宜");

                    countc = 0;
                    for (int i = 0; i < agriServiceIndices.size(); i++) {
                        tableCount++;
                        if (agriServiceIndices.get(i).getConditiontype().equals("预报")) {
                            if (agriServiceIndices.get(i).getWeatherelement().equals("降水")) {
                                String applystr = "";
                                if(agriServiceIndices.get(i).getCondition().contains("<=")){
                                    applystr = "Rain <= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains("<")){
                                    applystr = "Rain < " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">=")){
                                    applystr = "Rain >= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">")){
                                    applystr = "Rain > " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">",""));
                                }
                                List<TownshipForecast> rainData = townshipForecastMapper.selectList(Wrappers.<TownshipForecast>query()
                                        .select("Rain")
                                        .apply(applystr)
                                        .lambda()
                                        .eq(TownshipForecast::getDatechar, Timestamp.valueOf(dateChar))
                                        .eq(TownshipForecast::getTimechar, timeChar)
                                        .eq(TownshipForecast::getNtimes, Integer.parseInt(agriServiceIndices.get(i).getNtimes()))
                                        .eq(TownshipForecast::getStationid, townshipForecast.getStationid()));
                                if (rainData.size() > 0 && rainData.get(0).getRain() != null) {
                                    countc++;
                                }
                            }
                            if (agriServiceIndices.get(i).getWeatherelement().equals("温度")) {
                                String applystr = "";
                                if(agriServiceIndices.get(i).getCondition().contains("<=")){
                                    applystr = "(MaxTemp+MinTemp)/2 <= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains("<")){
                                    applystr = "(MaxTemp+MinTemp)/2 < " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">=")){
                                    applystr = "(MaxTemp+MinTemp)/2 >= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">")){
                                    applystr = "(MaxTemp+MinTemp)/2 > " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">",""));
                                }
                                List<TownshipForecast> maxTempData = townshipForecastMapper.selectList(Wrappers.<TownshipForecast>query()
                                        .select("(MaxTemp + MinTemp)/2 as MaxTemp")
                                        .apply(applystr)
                                        .lambda()
                                        .eq(TownshipForecast::getDatechar, Timestamp.valueOf(dateChar))
                                        .eq(TownshipForecast::getTimechar, timeChar)
                                        .eq(TownshipForecast::getNtimes, Integer.parseInt(agriServiceIndices.get(i).getNtimes()))
                                        .eq(TownshipForecast::getStationid, townshipForecast.getStationid()));
                                if (maxTempData.size() > 0 && maxTempData.get(0).getMaxtemp() != null) {
                                    countc++;
                                }
                            }
                            if (agriServiceIndices.get(i).getWeatherelement().equals("风速")) {
                                String applystr = "";
                                if(agriServiceIndices.get(i).getCondition().contains("<=")){
                                    applystr = "WindS <= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains("<")){
                                    applystr = "WindS < " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">=")){
                                    applystr = "WindS >= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">")){
                                    applystr = "WindS > " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">",""));
                                }
                                List<TownshipForecast> windSData = townshipForecastMapper.selectList(Wrappers.<TownshipForecast>query()
                                        .select("WindS")
                                        .apply(applystr)
                                        .lambda()
                                        .eq(TownshipForecast::getDatechar, Timestamp.valueOf(dateChar))
                                        .eq(TownshipForecast::getTimechar, timeChar)
                                        .eq(TownshipForecast::getNtimes, Integer.parseInt(agriServiceIndices.get(i).getNtimes()))
                                        .eq(TownshipForecast::getStationid, townshipForecast.getStationid()));
                                if (windSData.size() > 0 && windSData.get(0).getMaxtemp() != null) {
                                    countc++;
                                }
                            }
                            if (agriServiceIndices.get(i).getWeatherelement().equals("气压")) {
                                String applystr = "";
                                if(agriServiceIndices.get(i).getCondition().contains("<=")){
                                    applystr = "press <= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains("<")){
                                    applystr = "press < " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">=")){
                                    applystr = "press >= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">")){
                                    applystr = "press > " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">",""));
                                }
                                List<TownshipForecast> pressData = townshipForecastMapper.selectList(Wrappers.<TownshipForecast>query()
                                        .select("press")
                                        .apply(applystr)
                                        .lambda()
                                        .eq(TownshipForecast::getDatechar, Timestamp.valueOf(dateChar))
                                        .eq(TownshipForecast::getTimechar, timeChar)
                                        .eq(TownshipForecast::getNtimes, Integer.parseInt(agriServiceIndices.get(i).getNtimes()))
                                        .eq(TownshipForecast::getStationid, townshipForecast.getStationid()));
                                if (pressData.size() > 0 && pressData.get(0).getMaxtemp() != null) {
                                    countc++;
                                }
                            }
                            if (agriServiceIndices.get(i).getWeatherelement().equals("湿度")) {
                                String applystr = "";
                                if(agriServiceIndices.get(i).getCondition().contains("<=")){
                                    applystr = "Humid <= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains("<")){
                                    applystr = "Humid < " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">=")){
                                    applystr = "Humid >= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">=",""));
                                }
                                else if(agriServiceIndices.get(i).getCondition().contains(">")){
                                    applystr = "Humid > " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">",""));
                                }
                                List<TownshipForecast> humidData = townshipForecastMapper.selectList(Wrappers.<TownshipForecast>query()
                                        .select("Humid")
                                        .apply(applystr)
                                        .lambda()
                                        .eq(TownshipForecast::getDatechar, Timestamp.valueOf(dateChar))
                                        .eq(TownshipForecast::getTimechar, timeChar)
                                        .eq(TownshipForecast::getNtimes, Integer.parseInt(agriServiceIndices.get(i).getNtimes()))
                                        .eq(TownshipForecast::getStationid, townshipForecast.getStationid()));
                                if (humidData.size() > 0 && humidData.get(0).getMaxtemp() != null) {
                                    countc++;
                                }
                            }
                        } else {
                            String startDateStr = dateChar.split(" ")[0] + " " + timeChar + ":00:00";
                            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            Date startDate = sdf1.parse(startDateStr);
                            Date endDate = addHour(startDate, Integer.parseInt(agriServiceIndices.get(i).getNtimes()));
                            String endDateStr = sdf1.format(endDate);
                            if (agriServiceIndices.get(i).getWeatherelement().equals("降水")) {
                                if (agriServiceIndices.get(i).getWeatherelement().equals("降水")) {
                                    String applystr = "";
                                    if(agriServiceIndices.get(i).getCondition().contains("<=")){
                                        applystr = "sum(Rain) <= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<=",""));
                                    }
                                    else if(agriServiceIndices.get(i).getCondition().contains("<")){
                                        applystr = "sum(Rain) < " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace("<",""));
                                    }
                                    else if(agriServiceIndices.get(i).getCondition().contains(">=")){
                                        applystr = "sum(Rain) >= " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">=",""));
                                    }
                                    else if(agriServiceIndices.get(i).getCondition().contains(">")){
                                        applystr = "sum(Rain) > " + Double.parseDouble(agriServiceIndices.get(i).getCondition().replace(">",""));
                                    }
                                    List<MsgMediumSmallScale> msgMediumSmallScales = msgMediumSmallScaleMapper.selectList(Wrappers.<MsgMediumSmallScale>query()
                                            .select("sum(Rain) as rain,stationid,observtime")
                                            .lambda()
                                            .eq(MsgMediumSmallScale::getStationid, townshipForecast.getStationid())
                                            .between(MsgMediumSmallScale::getObservtime, Timestamp.valueOf(startDateStr), Timestamp.valueOf(endDateStr))
                                            .groupBy(MsgMediumSmallScale::getStationid, MsgMediumSmallScale::getObservtime)
                                            .having(applystr));
                                    if (msgMediumSmallScales.size() > 0 && msgMediumSmallScales.get(0).getRain() != null) {
                                        count++;
                                    }
                                }
                            }
                        }
                    }
                    //将预报存入数据库
                    AgriSrvFcst agriSrvFcst = new AgriSrvFcst();

                    if (count == tableCount) {
                        agriSrvFcst.setFarmservicesite(agriStation.getStrAgrStation());
//                        agriSrvFcst.setForecastdate(dateChar);
                        agriSrvFcst.setForecastdate(Timestamp.valueOf(dateChar));
                        agriSrvFcst.setTimechar(timeChar);
                        agriSrvFcst.setLon(String.valueOf(agriStation.getDLon()));
                        agriSrvFcst.setLat(String.valueOf(agriStation.getDLat()));
                        agriSrvFcst.setIndexname(indexName);
                        agriSrvFcst.setIndexlevel("适宜");
                        agriSrvFcst.setExplain("");
                        agriSrvFcstService.save(agriSrvFcst);
                    } else if (countc != 0) {
                        agriSrvFcst.setFarmservicesite(agriStation.getStrAgrStation());
//                        agriSrvFcst.setForecastdate(dateChar);
                        agriSrvFcst.setForecastdate(Timestamp.valueOf(dateChar));
                        agriSrvFcst.setTimechar(timeChar);
                        agriSrvFcst.setLon(String.valueOf(agriStation.getDLon()));
                        agriSrvFcst.setLat(String.valueOf(agriStation.getDLat()));
                        agriSrvFcst.setIndexname(indexName);
                        agriSrvFcst.setIndexlevel("不适宜");
                        agriSrvFcst.setExplain("");
                        agriSrvFcstService.save(agriSrvFcst);
                    } else {
                        agriSrvFcst.setFarmservicesite(agriStation.getStrAgrStation());
//                        agriSrvFcst.setForecastdate(dateChar);

                        agriSrvFcst.setForecastdate(Timestamp.valueOf(dateChar));
                        agriSrvFcst.setTimechar(timeChar);
                        agriSrvFcst.setLon(String.valueOf(agriStation.getDLon()));
                        agriSrvFcst.setLat(String.valueOf(agriStation.getDLat()));
                        agriSrvFcst.setIndexname(indexName);
                        agriSrvFcst.setIndexlevel("较适宜");
                        agriSrvFcst.setExplain("");
                        agriSrvFcstService.save(agriSrvFcst);
                    }

                }
            }
        }
        return true;
    }

    /**
     * 获取农业站点最近的区域自动站点
     *
     * @param lon
     * @param lat
     * @param townshipStations
     * @return
     */
    private TownshipStation getNearStation(double lon, double lat, List<TownshipStation> townshipStations) {
        double distance = calculateDistance(lon, lat, townshipStations.get(0).getLongitude(), townshipStations.get(0).getLatitude());
        TownshipStation nearStation = townshipStations.get(0);
        for (TownshipStation townshipStation : townshipStations) {
            double dis = calculateDistance(lon, lat, townshipStation.getLongitude(), townshipStation.getLatitude());
            if (dis < distance) {
                distance = dis;
                nearStation = townshipStation;
            }

        }
        return nearStation;
    }

    /**
     * 得到预报站点相近的农业站点
     */
    private List<AgriStationDto> getAgriStations(String stationId, List<MappingStation> mappingStations) {
        List<AgriStationDto> agriStationDtos = new ArrayList<>();
        for (MappingStation mappingStation : mappingStations) {
            if (mappingStation.getStrStaID().equals(stationId)) {
                AgriStationDto agriStationDto = new AgriStationDto();
                agriStationDto.setStrAgrStation(mappingStation.getStrAgrSta());
                agriStationDto.setStrAgrStationcode(mappingStation.getStrsataioncode());
                agriStationDto.setStrWCounty(mappingStation.getStrAgrCounty());
                agriStationDto.setDLon(mappingStation.getDAgrLon());
                agriStationDto.setDLat(mappingStation.getDAgrLat());
                agriStationDtos.add(agriStationDto);
            }
        }
        return agriStationDtos;

    }

    /**
     * 计算经纬度间距离
     *
     * @return
     */
    private double calculateDistance(double lon1, double lat1, double lon2, double lat2) {
        return 6371000 * Math.acos(
                Math.cos(Math.toRadians(lat1))
                        * Math.cos(Math.toRadians(lat2))
                        * Math.cos(Math.toRadians(lon2) - Math.toRadians(lon1))
                        + Math.sin(Math.toRadians(lat1))
                        * Math.sin(Math.toRadians(lat2))
        );
    }

    private Date addHour(Date date, int i) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.HOUR_OF_DAY, i);
        Date newDate = c.getTime();
        return newDate;
    }


    /************************
     * @Author : HuangDeYin Jolly
     * @Description : 此类是将数据存入到  喷药收晒施肥预报.doc 中并返回流
     * @param maker：制作人
     * @param forecastDate :制作日期
     * @param timeChar ：时次
     * @param indexName ：类型
     ************************/
    public Object dailyAgriculturalActivityForecast(String maker, String forecastDate, String timeChar, String indexName) {
        //文档名称 : 2023070608灌溉预报文档.docx
        String docName = forecastDate + timeChar + indexName + "预报文档.docx";
        //生成的文档的产品类型
        String productType = "日农事活动预报";
        //预报时间
        Timestamp forecastTime = DateUtil.localDateTimeToTimestamp(DateUtil.stringToLocalDateTime(forecastDate + " " + timeChar + ":00:00"));
        //文档制作时间
        Timestamp makeTime = DateUtil.localDateTimeToTimestamp(LocalDateTime.now());
        //查询数据
        List<AgriSrvFcstDto> agriSrvFcstDtoList = agriSrvFcstService.forecastQuery(forecastDate, timeChar, indexName);
        //判断是否有数据
        if (agriSrvFcstDtoList.isEmpty()) {
            return "无数据，无法生成文档，请联系管理员";
        }
        System.err.println(agriSrvFcstDtoList.size());

        //查询agri_product表是否已经存在
//        Integer id = agriProductMapper.selectId(docName, productType, forecastTime, makeTime, maker);
        Integer id = agriProductMapper.selectId1(docName, productType, forecastTime, maker);

        if (id == null) {
            //查询出agri_product表没有改文档
            //新建agriProduct类并设置数据
            AgriProduct agriProduct = new AgriProduct();
            //文档名称 : 2023070608灌溉预报文档.docx
            agriProduct.setProductname(docName);
            //产品类型
            agriProduct.setProducttype(productType);
            //预报时间
            agriProduct.setForecasttime(forecastTime);
            //制作时间
            agriProduct.setMaketime(makeTime);
            //制作人
            agriProduct.setMaker(maker);
            //状态
            agriProduct.setState("0");
            //插入数据到agri_product表，并返回插入的结果
            int insert = agriProductMapper.insert(agriProduct);
            log.debug("插入pg数据库的返回结果为： ->  " + insert);
            //如果插入数据成功
            if (insert > 0) {
                //将数据写入word文档
//                Integer id1 = agriProductMapper.selectId(docName, productType, forecastTime, makeTime, maker);
                Integer id1 = agriProductMapper.selectId1(docName, productType, forecastTime, maker);
                return docxToMongoDb(maker, forecastDate, timeChar, indexName, agriSrvFcstDtoList, id1, productType);
            } else {
                return "数据存入agri_product表失败，请联系管理员";
            }
        } else {
            //当pg数据库中有此信息时，查询mongo数据库中的信息
            HyDocFile docFileServiceById = docFileService.getById(String.valueOf(id));
            //mongo数据库中无此数据
            if (docFileServiceById == null) {
//                Integer id1 = agriProductMapper.selectId(docName, productType, forecastTime, makeTime, maker);
                Integer id1 = agriProductMapper.selectId1(docName, productType, forecastTime, maker);
                return docxToMongoDb(maker, forecastDate, timeChar, indexName, agriSrvFcstDtoList, id1, productType);
            } else {
                //mongo数据库中有此数据,则市界返回前端
                byte[] data = docFileServiceById.getData();
                HttpHeaders headers = new HttpHeaders();
                headers.setContentDispositionFormData("attachment", docName);
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                headers.setContentLength(data.length);
                return new ResponseEntity<>(data, headers, HttpStatus.OK);
            }
        }
    }


    /************************
     * @Author : HuangDeYin Jolly
     * @Description : 将docx文件存入到mongo中
     * @return org.springframework.http.ResponseEntity<byte [ ]> :
     ************************/
    public ResponseEntity<byte[]> docxToMongoDb(String maker, String forecastDate, String timeChar, String indexName, List<AgriSrvFcstDto> agriSrvFcstDtoList, Integer id, String productType) {
        ResponseEntity<byte[]> byteArrayResourceResponseEntity = dataToDocx(maker, forecastDate, timeChar, indexName, agriSrvFcstDtoList);
        if (byteArrayResourceResponseEntity.getStatusCode() == HttpStatus.OK) {
            byte[] byteArray = byteArrayResourceResponseEntity.getBody();
            // 保存进mongo
            HyDocFile hyDocFile = new HyDocFile();
            hyDocFile.setData(byteArray);
            hyDocFile.setId(String.valueOf(id));
            hyDocFile.setTable_name("agri_product");
            hyDocFile.setName(productType);
            HyDocFile save = docFileService.save(hyDocFile);
            return byteArrayResourceResponseEntity;
        } else {
            // 处理请求不成功的情况
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }


    /************************
     * @Author : HuangDeYin Jolly
     * @Description : 此类是将数据存入到  喷药收晒施肥预报.doc 中并返回流
     * @param maker：制作人
     * @param forecastDate :制作日期
     * @param timeChar ：时次
     * @param indexName ：类型
     * @param agriSrvFcstDtoList : 数据
     * @return org.springframework.http.ResponseEntity<byte [ ]> :
     ************************/

    public ResponseEntity<byte[]> dataToDocx(String maker, String forecastDate, String timeChar, String indexName, List<AgriSrvFcstDto> agriSrvFcstDtoList) {
        //文档名称 : 2023070608灌溉预报文档.docx
        String docName = forecastDate + timeChar + indexName + "预报文档.docx";
        // 模板文件路径
        String templateFilePath = "templates/dailyAgriculturalForecastTemp/喷药收晒施肥预报.docx";
        // 输出文件路径
        String outputFilePath = docFilePath + "/" + docName;
        //模板中需要更换的字段
        String signerPlaceholder = "[签发人]";
        String datePlaceholder = "[变更日期年月日]";
        String[] placeholders = new String[]{"[签发人]", "[变更日期年月日]"};
        String[] replacements = new String[]{maker, forecastDate};
        //DocxUtil.generateWordDocx(templateFilePath, outputFilePath, placeholders, replacements);
        //打开模板文档
        try (InputStream templateStream = new ClassPathResource(templateFilePath).getInputStream();
             XWPFDocument document = new XWPFDocument(templateStream);
             FileOutputStream outputStream = new FileOutputStream(outputFilePath);
             FileInputStream inputStream = new FileInputStream(outputFilePath);
             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()
        ) {
            // 替换签发人和日期
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                replaceTextInParagraph(paragraph, placeholders, replacements);
            }

            // 在文档中插入表格
            XWPFTable table = document.createTable(1, 7);  // 创建1行7列的表格
            table.getRow(0).getCell(0).setText("农服站点");
            table.getRow(0).getCell(1).setText("预报日期");
            table.getRow(0).getCell(2).setText("经度");
            table.getRow(0).getCell(3).setText("纬度");
            table.getRow(0).getCell(4).setText("指数名称");
            table.getRow(0).getCell(5).setText("指数等级");
            table.getRow(0).getCell(6).setText("说明");

            // 填充表格的数据
            agriSrvFcstDtoList.forEach(agriSrvFcstDto -> {
                XWPFTableRow dataRow = table.createRow();
                dataRow.getCell(0).setText(agriSrvFcstDto.getFarmservicesite());
                String trimmedDateString = agriSrvFcstDto.getForecastdate().trim();
                if (trimmedDateString.endsWith(" 20")) {
                    trimmedDateString = trimmedDateString.substring(0, trimmedDateString.length() - 2).trim();
                }
                dataRow.getCell(1).setText(DateUtil.convertDateFormat(trimmedDateString));
                DecimalFormat df = new DecimalFormat("0.000000");
                dataRow.getCell(2).setText(df.format(Double.parseDouble(agriSrvFcstDto.getLon())));
                dataRow.getCell(3).setText(df.format(Double.parseDouble(agriSrvFcstDto.getLat())));
                dataRow.getCell(4).setText(agriSrvFcstDto.getIndexname());
                dataRow.getCell(5).setText(agriSrvFcstDto.getIndexlevel());
                dataRow.getCell(6).setText(agriSrvFcstDto.getExplain());
            });

            templateStream.close();
            // 将生成的文档保存到输出文件
            document.write(outputStream);

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }

            byte[] byteArray = byteArrayOutputStream.toByteArray();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", docName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentLength(byteArray.length);

            return new ResponseEntity<>(byteArray, headers, HttpStatus.OK);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public List<String> selectIndexName() {
        return agriSrvFcstMapper.selectIndexName();
    }
}
